package com.spring.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.spring.adapter.LocationAdapter;
import com.spring.gowhere.R;
import com.spring.httputils.RequestParams;
import com.spring.httputils.RestClient;
import com.spring.httputils.TextHttpResponseHandler;
import com.spring.model.ContactData;
import com.spring.tool.App;
import com.spring.util.StatusBar;
import com.spring.util.SystemBarTintManager;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 一卡通帮助
 *
 * @param <MessageAdapter>
 * @author Administrator
 */
public class HelpActivity<MessageAdapter> extends AceActivity {
    private EditText querykq, querymycontay;
    private Button btnlogin;//
    private String queryStr;
    private RadioGroup rg;
    private Button queryselect;
    private String stredwebservicedaihao;
    public List<ContactData> contactList;
    private int index = 1;
    private MyHandler myHandler;
    private LinearLayout reservation_location01;
    private TextView location_text;
    String location_textStr;
    private String[] locations;
    private String[] urllocations;
    private String urllocation;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        //判断当前SDK版本号，如果是4.4以上，就是支持沉浸式状态栏的
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            new StatusBar(true, this);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.deep_bule);//通知栏所需颜色
        }
        setContentView(R.layout.help);
        TextView textView = (TextView) findViewById(R.id.title_tv);
        reservation_location01 = (LinearLayout) findViewById(R.id.reservation_location01);
        querymycontay = (EditText) findViewById(R.id.querymycontay);
        textView.setText("服务地址设置");
        myHandler = new MyHandler();
        ImageButton imageButton = (ImageButton) findViewById(R.id.title_left_ib);
        imageButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        rg = (RadioGroup) findViewById(R.id.rg);
        queryselect = (Button) findViewById(R.id.queryselect);
        rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                System.out.println(arg1);
                if (arg1 == R.id.male) {
                    System.out.println("male");
                    findViewById(R.id.reservation_location01).setVisibility(View.GONE);
                    findViewById(R.id.linearlayout01).setVisibility(View.VISIBLE);
                    queryselect.setVisibility(View.GONE);
                    btnlogin.setVisibility(View.VISIBLE);
                    location.setVisibility(View.GONE);
                    querykq.setVisibility(View.VISIBLE);
                } else if (arg1 == R.id.female) {
                    System.out.println("female");
                    findViewById(R.id.reservation_location01).setVisibility(View.VISIBLE);
                    findViewById(R.id.linearlayout01).setVisibility(View.GONE);
                    queryselect.setVisibility(View.VISIBLE);
                    btnlogin.setVisibility(View.GONE);
                    location.setVisibility(View.GONE);
                    querymycontay.setVisibility(View.VISIBLE);
                }
            }
        });

        location = (RelativeLayout) findViewById(R.id.reservation_location3);
        location_text = (TextView) findViewById(R.id.reservation_location_text);
        location.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                new LocationDialog(HelpActivity.this).show();
            }
        });
        btnlogin = (Button) findViewById(R.id.btnlogin);
        querykq = (EditText) findViewById(R.id.querykq);
        querykq.setText(App.getInstance().url);
        btnlogin.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                queryStr = querykq.getText().toString();
                if (queryStr != null && !queryStr.equals("")) {
                    App.getInstance().setApiUrl(queryStr);
                    Toast.makeText(HelpActivity.this, "服务器地址设置成功请重新登录",  Toast.LENGTH_SHORT).show();
                    SharedPreferences userInfo = getSharedPreferences(
                            "user_info", 0);
                    userInfo.edit().putBoolean("login", false).commit();
                    Intent intent = new Intent(HelpActivity.this,
                            LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        });

        queryselect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                stredwebservicedaihao = querymycontay.getText().toString();
                if (stredwebservicedaihao != null
                        && !"".equals(stredwebservicedaihao)) {
                    restClient = new RestClient(HelpActivity.this);
                    SendHttpDate(stredwebservicedaihao);
                }
            }
        });
    }

    private void SendHttpDate(String stredwebservicedaihao) {
        String url = "http://120.237.110.50:8022/WebService.asmx/QueryContactList";
        RequestParams requestparams = new RequestParams(url, "POST");
        requestparams.put("ContactCaption", stredwebservicedaihao);
        requestparams.put("PageIndex", "" + index);

        TextHttpResponseHandler textHttpResponseHandler = new TextHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  String responseString) {
                // TODO Auto-generated method stub
                Log.e("TAG", "responseString---" + responseString);
                if (responseString != null && !"".equals(responseString)) {
                    AnalysisData(responseString);
                }

            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                // TODO Auto-generated method stub
                Log.e("TAG", "responseString---" + responseString);
                // AnalysisData(responseString);

            }
        };
        try {
            restClient.post(url, requestparams, textHttpResponseHandler);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * json数据解析
     *
     * @param strResult
     * @throws JSONException
     */
    private void AnalysisData(String strResult) {
        /**
         * 这里需要分析服务器回传的json格式数据，
         */
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(strResult);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            JSONArray jsonarray = jsonObject.getJSONArray("ContactList");
            contactList = new ArrayList<ContactData>();
            for (int i = 0; i < jsonarray.length(); i++) {
                JSONObject json = jsonarray.getJSONObject(i);
                ContactData contactData = new ContactData();
                contactData.setContactCaption(json.getString("ContactCaption"));
                contactData.setAddr(json.getString("Addr"));
                contactData.setLinkMan(json.getString("LinkMan"));
                contactData.setLinkTel(json.getString("LinkTel"));
                contactData.setLinkUrl(json.getString("LinkUrl"));
                contactData.setWebSrvUrl(json.getString("WebSrvUrl"));
                contactList.add(contactData);

            }
            locations = new String[contactList.size()];
            urllocations = new String[contactList.size()];
            for (int i = 0; i < contactList.size(); i++) {
                locations[i] = contactList.get(i).getContactCaption();
                urllocations[i] = contactList.get(i).getWebSrvUrl();
            }
            if (contactList != null && contactList.size() > 0) {
                Message msg = new Message();
                msg.arg1 = 1;
                HelpActivity.this.myHandler.sendMessage(msg); // 向Handler发送消息,更新UI
            } else {
                Toast.makeText(HelpActivity.this, "没有查询到相关数据",  Toast.LENGTH_SHORT).show();
            }


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 接受消息,处理消息 ,此Handler会与当前主线程一块运行
     */

    class MyHandler extends Handler {
        public MyHandler() {
        }

        public MyHandler(Looper L) {
            super(L);
        }

        // 子类必须重写此方法,接受数据
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            Log.d("MyHandler", "handleMessage......");
            super.handleMessage(msg);
            // 此处可以更新UI
            switch (msg.arg1) {
                case 1:
                    if (contactList != null && contactList.size() > 0) {
                        location.setVisibility(View.VISIBLE);
                        btnlogin.setVisibility(View.GONE);
//					reservation_location01.setVisibility(View.GONE);
                        querymycontay.setVisibility(View.GONE);
                        querykq.setVisibility(View.GONE);
                        new LocationDialog(HelpActivity.this).show();
                    }

                    break;
                case 2:
                    break;
                default:
                    break;
            }

        }
    }


    public class LocationDialog extends Dialog {

        public LocationDialog(Context context) {
            super(context, R.style.myDialog);
            // TODO Auto-generated constructor stub
        }

        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.indicatorsdialog);
            DisplayMetrics dm = new DisplayMetrics();
            Window window = getWindow();
            // 取得窗口属性
            window.getWindowManager().getDefaultDisplay().getMetrics(dm);
            // 屏幕的宽度
            int screenWidth = dm.widthPixels;
            WindowManager.LayoutParams wl = window.getAttributes();
            wl.width = screenWidth - dip2px(this.getContext(), 30);
            window.setAttributes(wl);

            ListView listview = (ListView) findViewById(R.id.indicators_list);
            LocationAdapter adapter = new LocationAdapter(HelpActivity.this,
                    "0");
            adapter.setLocation(locations);
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long i) {
                    location_text.setText(locations[position]);
                    location_textStr = locations[position];
                    urllocation = urllocations[position];
                    App.getInstance().url = urllocation;

                    dismiss();
                    Toast.makeText(HelpActivity.this, "服务器地址设置成功请登录",  Toast.LENGTH_SHORT).show();
                    SharedPreferences userInfo = getSharedPreferences(
                            "user_info", 0);
                    userInfo.edit().putBoolean("login", false).commit();
                    Intent intent = new Intent(HelpActivity.this,
                            LoginActivity.class);
                    startActivity(intent);
                }
            });
        }

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            locations = null;
            location.setVisibility(View.GONE);
            reservation_location01.setVisibility(View.VISIBLE);
            queryselect.setVisibility(View.VISIBLE);
            btnlogin.setVisibility(View.GONE);
            location.setVisibility(View.GONE);
            querymycontay.setVisibility(View.VISIBLE);

            return super.onKeyDown(keyCode, event);
        }
    }

}
